/* Javascript for the main page */

"use strict";

function startup() {

	Globalize.culture("en-GB");

	$("#loginButton").click(loginButtonClicked);
	$("#logoutButton").click(logoutButtonClicked);

	/* Make it log in if you hit the enter key on either text fields */

	$("#loginId").keyup(function(key) {
		if (key.which == enterKey) {
			loginButtonClicked();
		}
	});

	$("#password").keyup(function(key) {
		if (key.which == enterKey) {
			loginButtonClicked();
		}
	});

	$("#rememberMeCheckBox").keyup(function(key) {
		if (key.which == enterKey) {
			loginButtonClicked();
		}
	});

	$("#homePageLink").click(function(event) {
		homePageLinkClick(event);
	});

	$("#searchTextField").keyup(function(key) {
		if (key.which == enterKey) {
			queryString = $("#searchTextField").val();
			searchThreads(queryString, 0, 40);
		}
	});

	/* Ensure that whenever you press the back button, we display the right page */

	$(window).bind('hashchange', function(e) {
		processUrl();
	});

	/* Take you to the right page and log you in if necessary */
	processUrl();
}

/* Display boards, site and potentially user information, if the user is auto logged in. */

function frontPageDisplay(data) {

	/* If you're autologging in, we'll have a user fragment, so display the user data */

	userDisplay(data);
	boardDisplay(data);
	siteInfoDisplay(data);
}

function frontPageCallback(data, status, request) {
	frontPageDisplay(data);
}

function frontPageRequest(loginId, encryptedPassword) {

	var xml = "<Requests>";

	/* If you pass a login ID and encrypted password, then also request a login and get the user info back */

	if (loginId == null) {
		xml += siteInfoMessage();
		xml += boardsMessage();
		xml += userInfoMessage();
	} else {
		xml += loginMessage(loginId, encryptedPassword, true, false);
		xml += siteInfoMessage();
		xml += boardsMessage();
		xml += userInfoMessage();
	}

	xml += "</Requests>";

	sendMessage(xml, frontPageCallback);
}

function homePageLinkClick(event) {

	var loginId = localStorage.getItem(loginIdKey);
	var encryptedPassword = localStorage.getItem(encryptedPasswordKey);

	frontPageRequest(loginId, encryptedPassword);

}